// pages/info/info.js
import { showModal,login,checkSession,getSetting,getLocation} from '../../utils/asyncwx.js'
const http = require('../../utils/http.js');
import regeneratorRuntime from '../../lib/runtime/runtime'
const QQMapWX = require('../../lib/qqmap-wx-jssdk.js');
let qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: ['湖南省', '长沙市', '雨花区'],
    add1:null,
    add2:null,
    add3:null,
    add4:null,
    uid: null,
    unit:null,
    disabled:false,
    phoneNum: '',
    tname: '',
    userInfo:{} //用户信息对象
  },
  toback: function () {
    //返回
    wx.navigateBack({
      delta: 1
    });

  },// end of toback
  addnameInfo: function (e) {
    //姓名输入
    let tname = e.detail.value
    this.setData({
      tname: tname
    })
    //console.log('tname =' + tname)
  },
  addUnitInfo: function (e) {
    // unit输入
    // console.log('inputPhoneNum 函数')
    let unit= e.detail.value
    this.setData({
      unit: unit
    })
   
    
  },
  inputPhoneNum: function (e) {
    // 手机号码输入
    // console.log('inputPhoneNum 函数')
    let phoneNum = e.detail.value
    this.setData({
      phoneNum: phoneNum
    })
    //console.log('phoneNum =' + phoneNum)
      //this.hideSendMsg()
    
  },
  async getPhoneNumber(e) { 
    //console.log(e.detail.errMsg) 
    //console.log(e.detail.iv) 
    //console.log(e.detail.encryptedData) 
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny' ||e.detail.errMsg == 'getPhoneNumber:fail Error: 该 appid 没有权限'||e.detail.errMsg =='getPhoneNumber:fail:access denied'){
      await showModal({content:'请允许获取手机号码!',showCancel:false})   
     
    } else {
        //同意授权获取手机号码
        // 判断session是否有效 
        let session_key=null 
      
        let res=await checkSession()
        
        if (res.errMsg=='checkSession:ok'){
          //  session_key 未过期，并且在本生命周期一直有效
          // console.log("session_key 未过期，并且在本生命周期一直有效")
          session_key=wx.getStorageSync('session_key')
          
         
        }else{
            // session_key 已经失效，需要重新执行登录流程
            // 重新登录
          this.relogin()

        }
       
        
       let url='wx/getPhoneNumber/'
       let data={ 
          encryptedData: e.detail.encryptedData,//encodeURIComponent(e.detail.encryptedData),
          iv: e.detail.iv,
          session_key: session_key
       }
    
       let res1= await http.post(url,data)
      
    
        //存入手机号码
          let phoneNum=res1.phoneNoInfo
          this.setData({
            phoneNum
          })        
      


    }
  },

  async checkregion() {
    if (this.data.add2=='请选择'){
      await showModal({content:'请选择地区!',showCancel:false})     
      return false
    } 
    if (this.data.add3=='请选择'){
      await showModal({content:'请选择地区!',showCancel:false})
      return false
    }
    return true
    
  },
  async relogin(){
   
    let {code}=await login() //2.获取小程序登录成功后的code     
    let data = {
      code: code
    }
   //3.发送请求获取用的session_key
 
    const url = 'wx/getopenid/'
    let res= await http.post(url,data)
             
    let session_key=res.sessionKey
    wx.setStorageSync('session_key', session_key)
  },
  async checktname(tname) {
    
    if(tname===null){
      await showModal({content:'请输入姓名!',showCancel:false})
      return false

    }
    if (tname.length>1){
      return true
    } else {
      await showModal({content:'姓名长度至少2个字符!',showCancel:false})
      return false
    }
  },
  async checkunit(unit) {
    
    if(unit===null){
      await showModal({content:'请输入单位!',showCancel:false})
      return false

    }
    if (unit.length>1){
      return true
    } else {
      await showModal({content:'单位长度至少2个字符!',showCancel:false})
      return false
    }
  },
  async getUserLocation () {
   
    const res =await getSetting()
   // console.log(JSON.stringify(res))
    if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) 
    {
      await showModal({content:'地理位置授权失败，请选择地区!',showCancel:false})
    }else{
      this.getLocation()
    }
    
  },
  // 微信获得经纬度
  async getLocation() {
    let res= await getLocation()
    let latitude = res.latitude
    let longitude = res.longitude
    //var speed = res.speed
   // var accuracy = res.accuracy;
    this.getLocal(latitude, longitude)
    /*
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        //console.log(JSON.stringify(res))
       
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
        await showModal({content:'地理位置获取失败，请选择地区!',showCancel:false})
      }
    })*/

  },
  // 获取当前地理位置
   getLocal (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
    
         if (res.status==0){
          let add1 = res.result.address_component.province
          let add2 = res.result.address_component.city
          let add3 = res.result.address_component.district
          let add4 = res.result.address_component.street
          let  region=[]
          region.push(add1,add2,add3)
          vm.setData({
            region,
            add1,
            add2,
            add3,
            add4
          })
        }else{
           showModal({content:'地理位置解析失败，请选择地区!',showCancel:false})
        }
        
 
      },
      fail: function (res) {
         showModal({content:'地理位置处理失败，请选择地区!',showCancel:false})
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },

  RegionChange: function(e) {
    //地区选择
    const add1=e.detail.value[0]
    const add2=e.detail.value[1]
    const add3=e.detail.value[2]
    const region=e.detail.value
    this.setData({
      region,
      add1,
      add2,
      add3
    })
   
    
  },
  async checkPhoneNum(phoneNum) {
    //检查手机格式是否正确
    let str = /^1[3-9][0-9]\d{8}$/  // if (!value.tel.match(/^1[3-9][0-9]\d{8}$/)) {
    if (str.test(phoneNum)) {
      return true
    } else {
      await showModal({content:'手机号格式不正确!',showCancel:false})
      return false
    }
  },
  async get_data() {
    //获取信息    
     const uid=this.data.uid
     if (uid){
       let url = 'Client/getbalance/';
       let data = {
         uid: this.data.uid,
       }
     let res= await http.post(url,data)
   
     if (res){
      const add1=res.client.add1||'湖南省'
      const add2=res.client.add2||'请选择'
      const add3=res.client.add3||'请选择'
      const add4=res.client.add4
       
      let  region=[]
      region.push(add1,add2,add3)
          
       this.setData({         
            
            tname: res.client.name,
            phoneNum: res.client.tel,
            unit: res.client.unit,
            add1,
            add2,
            add3,
            add4,
            region
          })      
      
      }
     }
      
   },
  async dosubmit() {
   
    //提交数据
    let uid = this.data.uid//+" "+ pdname
    let phoneNum = this.data.phoneNum
    let tname = this.data.tname
    let unit = this.data.unit
    const add1=this.data.add1
    const add2=this.data.add2
    const add3=this.data.add3
    const add4=this.data.add4
    const shareuid=wx.getStorageSync("shareuid")
    //console.log('shareuid=',shareuid)
    let url = 'Client/edit/'    
    
    let data = {
      add1:add1,
      add2:add2,
      add3:add3,
      add4:add4,
      id: uid,
      tel: phoneNum,
      name: tname,
      unit:unit,
      shareuid:shareuid
     
    }
    
    let res= await http.post(url,data)
    if (res){
      
        wx.setStorageSync('role',res.role)
        //跳转到个人中心
        await showModal({content:'修改信息成功!',showCancel:false})
        wx.switchTab({
          url: '/pages/user/index'
        })
       
      
    }
   
  }, 
  async submitForm(e) {
    //提交表单
     //1 。判断缓存中有没有token
     const token=wx.getStorageSync("token")
     //console.log('handle_pay token=',token)
     // 2.判断
     if(!token){        
       wx.navigateTo( //跳转到授权页面
         {url:'/pages/login/index'}
       )
       return false
     } 
    
    let phoneNum = this.data.phoneNum
    let tname = this.data.tname
    let unit = this.data.unit

    
    let checkedNum = await this.checkPhoneNum(phoneNum)
    let checktname=await this.checktname(tname)
    let checkunit=await this.checkunit(unit)
    let checkregion=await this.checkregion()
   
    if( (checkedNum)&& (checktname)&&(checkregion)&&(checkunit)) {
        
        //  console.log('phoneNum' + this.data.phoneNum)
        this.dosubmit()
        
      }
    

  },  
  async gettoken(){
    //从后台获取token
    let url = 'wx/login/'
    let data = {
      uid: this.data.uid,     
    }
    let res= await http.post(url,data)
   
    if(res){
      wx.setStorageSync('token',res)
    }
    

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key:'462BZ-NW2C3-GQO3M-YKW7B-HVTN2-AIBDN'//开发者的key
    })
   
  },

 

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    const userInfo=wx.getStorageSync("userInfo")
    const uid=wx.getStorageSync("uid")
    this.setData({
      userInfo,
      uid
    })
    
    this.gettoken()
    this.relogin()
    this.get_data() 
  }

  
 
})